from typing import Any

from aiogram import types
from aiogram_dialog import Dialog, DialogManager, Window
from aiogram_dialog.widgets.kbd import Button, Cancel, Row, ScrollingGroup, Select
from aiogram_dialog.widgets.text import Format

from app.bot.dialog.dialog_states import OrderDetailsSG, UserOrdersSG
from app.bot.dialog.getters.users import user_orders_getter
from app.bot.dialog.widgets import LocaleText


async def display_order_details(
    call: types.CallbackQuery, widget: Any, manager: DialogManager, order_id: str
):
    await manager.start(OrderDetailsSG.order_details, {"order_id": int(order_id)})


async def display_orders(
    call: types.CallbackQuery, widget: Any, manager: DialogManager
):
    manager.dialog_data["user_id"] = manager.start_data.get("user_id")
    manager.dialog_data["orders_status"] = widget.widget_id

    if widget.widget_id == "active":
        await manager.switch_to(UserOrdersSG.user_orders_active)
    else:
        await manager.switch_to(UserOrdersSG.user_orders_archive)


orders_history_window = Window(
    LocaleText("orders-history"),
    Row(
        Button(LocaleText("orders-active"), id="active", on_click=display_orders),
        Button(LocaleText("orders-archive"), id="archive", on_click=display_orders),
    ),
    Cancel(LocaleText("back-btn")),
    state=UserOrdersSG.orders_history,
)

orders_active_window = Window(
    LocaleText("orders-active"),
    ScrollingGroup(
        Select(
            Format("№{item.id} {item.summ}$ {item.was_created}"),
            "user_orders_sel",
            lambda order: order.id,
            "user_orders",
            on_click=display_order_details,
        ),
        width=2,
        height=4,
        id="useritemssel",
    ),
    Cancel(LocaleText("back-btn")),
    state=UserOrdersSG.user_orders_active,
    getter=user_orders_getter,
)

orders_archive_window = Window(
    LocaleText("orders-archive"),
    ScrollingGroup(
        Select(
            Format("{item.summ}$ {item.was_created}"),
            "user_orders_sel",
            lambda order: order.id,
            "user_orders",
            on_click=display_order_details,
        ),
        width=2,
        height=4,
        id="useritemssel",
    ),
    Cancel(LocaleText("back-btn")),
    state=UserOrdersSG.user_orders_archive,
    getter=user_orders_getter,
)

orders_history_dialog = Dialog(
    orders_history_window,
    orders_active_window,
    orders_archive_window,
)


async def user_orders(
    message: types.Message, widget: Any, dialog_manager: DialogManager
):
    user_id = message.from_user.id

    await dialog_manager.start(
        UserOrdersSG.orders_history,
        {"user_id": user_id, "orders_type": widget.widget_id},
    )
